<template>

    <ConfirmDialog></ConfirmDialog>
    <section class="homeCanvas">
        <div class="canvasPasswords">
            <DataView :value="filteredData" paginator :rows="10" :rowsPerPageOptions="[10, 20, 30]" :layout="layout">
                <template #paginatorend>
                    <div class="paginatorNav">
                        <InputText type="text" v-model="valueSearch" placeholder="Поиск..."></InputText>
                        <DataViewLayoutOptions v-model="layout" />
                    </div>
                </template>

                <template #grid="filteredData">
                    <TransitionGroup name="list">
                    <div v-for="(obj, index) in filteredData.items" :key="index">
                        <div v-if="obj.visible" class="passwordCard">
                            <Card>
                                <template #title>
                                    <div class="passwordCardTitle">
                                        <div class="passwordCardTitle__Text">{{ obj.title }}</div>
                                        <i @click="togglePasswordVisibility(obj)" class="pi pi-eye-slash" style="color: 'var(--primary-color)'; font-size: 2.5rem;"></i>
                                    </div>
                                </template>
                                <template #content>
                                    <p>{{ obj.login }}</p>
                                    <p>{{ obj.password }}</p>
                                    <div class="passwordIcons">
                                        <div class="passwordIcons__primary">
                                            <i @click="copyPassword(index)" v-tooltip.bottom="'Скопировать'" type="text" placeholder="Bottom" class="pi pi-copy" style="color: 'var(--primary-color)'; font-size: 1.5rem;"></i>
                                            <i @click="editModalOpen(obj)" v-tooltip.bottom="'Редактировать'" type="text" placeholder="Bottom" class="pi pi-file-edit" style="color: 'var(--primary-color)'; font-size: 1.5rem;"></i>
                                            <i v-if="obj.shared !== true" v-tooltip.bottom="'Поделиться'" type="text" placeholder="Bottom" @click="shareModalOpen(obj)" class="pi pi-file-export" style="color: 'var(--primary-color)'; font-size: 1.5rem;"></i>
                                        </div>                            
                                        <i @click="confirmModalOpen(obj)" v-tooltip.bottom="'Удалить'" type="text" placeholder="Bottom" class="pi pi-file-excel" style="color: 'var(--primary-color)'; font-size: 1.5rem;"></i>
                                    </div>
                                </template>
                            </Card>
                        </div>

                        <div v-else class="passwordCard">
                            <Card>
                                <template #title>
                                    <div class="passwordCardTitle">
                                        <div class="passwordCardTitle__Text">{{ obj.title }}</div>
                                        <i @click="togglePasswordVisibility(obj)" class="pi pi-eye" style="color: 'var(--primary-color)'; font-size: 2.5rem;"></i>
                                    </div>
                                </template>
                                <template #content>
                                    <p>********</p>
                                    <p>********</p>
                                    <div class="passwordIcons">
                                        <div class="passwordIcons__primary">
                                            <i @click="copyPassword(index)" v-tooltip.bottom="'Скопировать'" type="text" placeholder="Bottom" class="pi pi-copy" style="color: 'var(--primary-color)'; font-size: 1.5rem;"></i>
                                            <i @click="editModalOpen(obj)" v-tooltip.bottom="'Редактировать'" type="text" placeholder="Bottom" class="pi pi-file-edit" style="color: 'var(--primary-color)'; font-size: 1.5rem;"></i>
                                            <i v-if="obj.shared !== true" @click="shareModalOpen(obj)" v-tooltip.bottom="'Поделиться'" type="text" placeholder="Bottom" class="pi pi-file-export" style="color: 'var(--primary-color)'; font-size: 1.5rem;"></i>
                                        </div>
                                        <i @click="confirmModalOpen(obj)" v-tooltip.bottom="'Удалить'" type="text" placeholder="Bottom" class="pi pi-file-excel" style="color: 'var(--primary-color)'; font-size: 1.5rem;"></i>
                                    </div>
                                </template>
                            </Card>
                        </div>
                    </div>
                    </TransitionGroup>
                </template>

                <template #list="filteredData">
                        <div v-for="(obj, index) in filteredData.items" :key="index" class="passwordPanel">
                            <div v-if="obj.visible">
                                <div class="passwordPanel__title">
                                    <i @click="togglePasswordVisibility(obj)" class="pi pi-eye-slash" style="color: 'var(--primary-color)'; font-size: 2rem;"></i>
                                    <p>{{ obj.title }}</p>
                                </div>
                                <div class="passwordPanel__main">
                                    <div class="passwordPanel__mainText">
                                        <p class="passwordPanel__mainText__left">{{ obj.login }}</p>
                                        <p>{{ obj.password }}</p>
                                    </div>
                                    <div class="passwordPanel__icons">
                                        <i @click="copyPassword(index)" v-tooltip.bottom="'Скопировать'" type="text" placeholder="Bottom" class="pi pi-copy" style="color: 'var(--primary-color)'; font-size: 1.5rem;"></i>
                                        <i @click="editModalOpen(obj)" v-tooltip.bottom="'Редактировать'" type="text" placeholder="Bottom" class="pi pi-file-edit" style="color: 'var(--primary-color)'; font-size: 1.5rem;"></i>
                                        <i v-if="obj.shared !== true" @click="shareModalOpen(obj)" v-tooltip.bottom="'Поделиться'" type="text" placeholder="Bottom" class="pi pi-file-export" style="color: 'var(--primary-color)'; font-size: 1.5rem;"></i>
                                        <i @click="confirmModalOpen(obj)" v-tooltip.bottom="'Удалить'" type="text" placeholder="Bottom" class="pi pi-file-excel" style="color: 'var(--primary-color)'; font-size: 1.5rem;"></i>
                                    </div>
                                </div>
                                <Divider />
                            </div>

                            <div v-else>
                                <div class="passwordPanel__title">
                                    <i @click="togglePasswordVisibility(obj)" class="pi pi-eye" style="color: 'var(--primary-color)'; font-size: 2rem;"></i>
                                    <p>{{ obj.title }}</p>
                                </div>
                                <div class="passwordPanel__main">
                                    <div class="passwordPanel__mainText">
                                        <p class="passwordPanel__mainText__left"></p>
                                        <p></p>
                                    </div>
                                    <div class="passwordPanel__icons">
                                        <i @click="copyPassword(index)" v-tooltip.bottom="'Скопировать'" type="text" placeholder="Bottom" class="pi pi-copy" style="color: 'var(--primary-color)'; font-size: 1.5rem;"></i>
                                        <i @click="editModalOpen(obj)" v-tooltip.bottom="'Редактировать'" type="text" placeholder="Bottom" class="pi pi-file-edit" style="color: 'var(--primary-color)'; font-size: 1.5rem;"></i>
                                        <i v-if="obj.shared !== true" @click="shareModalOpen(obj)" v-tooltip.bottom="'Поделиться'" type="text" placeholder="Bottom" class="pi pi-file-export" style="color: 'var(--primary-color)'; font-size: 1.5rem;"></i>
                                        <i @click="confirmModalOpen(obj)" v-tooltip.bottom="'Удалить'" type="text" placeholder="Bottom" class="pi pi-file-excel" style="color: 'var(--primary-color)'; font-size: 1.5rem;"></i>
                                    </div>
                                </div>
                                <Divider />
                            </div>
                        </div>
                </template>

            </DataView>
        </div>

        
        <Divider />
        <div class="canvasDial">
            <SpeedDial :model="dialLinks" direction="up" :style="{ left: 'calc(50% - 2rem)', bottom: 0 }" />
            <Toast />
        </div>

        <div>
            <Dialog v-model:visible="visibleAddModal" modal header="Новый паролус" :style="{ width: '50rem' }" :breakpoints="{ '1199px': '75vw', '575px': '90vw' }">
                <div v-if="isGenerated" class="passwordCreationModal__Generated">
                    <p id="generated">{{ generatedPassword }}</p>
                    <div v-if="isCopied">
                        <i @click="copyGenerated" class="pi pi-check" style="color: 'var(--primary-color)'; font-size: 1.5rem;"></i>
                    </div>
                    <div v-else>
                        <i @click="copyGenerated" class="pi pi-copy" style="color: 'var(--primary-color)'; font-size: 1.5rem;"></i>
                    </div>
                </div>
                <div v-else>
                    <p class="passwordCreationModal__Help">Сильный паролус имеет минимум 8 символов, 1 заглавную и 1 цифру - можете сгенерировать его мгновенно</p>
                    <Button label="Сгенерировать" icon="pi pi-bolt" @click="generatePassword" />
                </div>
                <div id="passwordCreationModal">
                    <InputText type="text" v-model="valueTitle" aria-describedby="title-help" @keyup.enter="addParolus" />
                    <small id="title-help">Название паролуса</small>

                    <InputText type="text" v-model="valueLogin" aria-describedby="login-help" @keyup.enter="addParolus" />
                    <small id="login-help">Введите логин паролуса</small>

                    <Password v-model="valuePassword" promptLabel="Сила паролуса" weakLabel="Слабый" mediumLabel="Средний" strongLabel="Сильный" inputId="password" aria-describedby="password-help" @keyup.enter="addParolus" toggleMask />
                    <small id="password-help">Введите пароль паролуса</small>

                    <Button label="Сохранить" icon="pi pi-external-link" @click="addParolus" />
                </div>
            </Dialog>
        </div>

        <div>
            <Dialog v-model:visible="visibleEditModal" modal header="Изменение паролуса" :style="{ width: '50rem' }" :breakpoints="{ '1199px': '75vw', '575px': '90vw' }">
                <div id="passwordCreationModal">
                    <InputText type="text" v-model="valueTitle" aria-describedby="title-help" @keyup.enter="editParolus" />
                    <small id="title-help">Название паролуса</small>

                    <InputText type="text" v-model="valueLogin" aria-describedby="login-help" @keyup.enter="editParolus" />
                    <small id="login-help">Введите логин паролуса</small>

                    <Password v-model="valuePassword" promptLabel="Сила паролуса" weakLabel="Слабый" mediumLabel="Средний" strongLabel="Сильный" inputId="password" aria-describedby="password-help" @keyup.enter="editParolus" toggleMask />
                    <small id="password-help">Введите пароль паролуса</small>

                    <Button label="Изменить" icon="pi pi-external-link" @click="editParolus" />
                </div>
            </Dialog>
        </div>

        <div>
            <Dialog v-model:visible="visibleAboutModal" modal header="Профиль" :style="{ width: '50rem' }" :breakpoints="{ '1199px': '75vw', '575px': '90vw' }">
                <div id="aboutModal">
                    <TabView>
                        <TabPanel header="Аккаунт">
                            <p>
                                Ваш UID: {{ store.state.userID }}
                            </p>
                            <Divider />
                            <div v-if="isRecievingShares">
                                <h5>Паролус-шаринг (пользователи смогут делиться с вами паролусами)</h5>
                                <div v-if="isCooldown">
                                    <p>Вы сможете переключить статус через: {{ remainingCooldown }} секунд</p>
                                    <InputSwitch v-model="recieving" disabled />
                                </div>
                                <div v-else>
                                    <InputSwitch v-model="recieving" />
                                </div>
                            </div>
                            <div>
                                <h5>Управление аккаунтом</h5>
                                <Password v-model="passwordChange" placeholder="Новый паролус..." promptLabel="Сила паролуса" weakLabel="Слабый паролус" mediumLabel="Средний паролус" strongLabel="Сильный паролус" @keyup.enter="changePass" toggleMask />
                            </div>
                            <div>
                                <Button @click="changePass" label="Смена пароля" icon="pi pi-key" />
                            </div>
                            <div>
                                <Button @click="confirmDeleteSelfAccountModalOpen()" label="Удаление аккаунта" icon="pi pi-exclamation-triangle" />
                            </div>
                        </TabPanel>
                        <TabPanel header="Контакты">
                            <div class="aboutModal__ContactInfo">
                                <i class="pi pi-code" style="color: 'var(--primary-color)'; font-size: 1.5rem;"></i>
                                https://gitverse.ru/internetfriend/parolus
                            </div>
                            <div class="aboutModal__ContactInfo">
                                2024, Москва
                            </div>
                        </TabPanel>
                        <TabPanel header="Интерфейс">
                            <Dropdown v-model="selectedTheme" :options="themes" optionLabel="name" placeholder="Выберите цвет интерфейса" />
                        </TabPanel>
                    </TabView>
                </div>
            </Dialog>
        </div>

        <div>
            <Dialog v-model:visible="visibleConfirmDelete" modal header="Удалить паролус?" :style="{ width: '50rem' }" :breakpoints="{ '1199px': '75vw', '575px': '90vw' }">
                <div class="confirmButtons">
                    <Button @click="closeConfirm" label="Отменить" severity="secondary" outlined />
                    <Button @click="deleteParolus" label="Удалить" severity="danger" outlined />
                </div>
            </Dialog>
        </div>

        <div>
            <Dialog v-model:visible="visibleConfirmDeleteSelfAccount" modal header="Вы уверены, что хотите удалить аккаунт и все паролусы?" :style="{ width: '50rem' }" :breakpoints="{ '1199px': '75vw', '575px': '90vw' }">
                <p>Не забудьте экспортировать все паролусы перед удалением аккаунта!</p>
                <div class="confirmButtons">
                    <Button @click="closeConfirm" label="Отменить" severity="secondary" outlined />
                    <Button @click="deleteSelfUserAccount" label="Удалить" severity="danger" outlined />
                </div>
            </Dialog>
        </div>

        <div>
            <Dialog v-model:visible="visibleShareModal" modal header="Поделиться паролусом" :style="{ width: '50rem' }" :breakpoints="{ '1199px': '75vw', '575px': '90vw' }">
                <p>Вы можете поделиться паролусом только с теми пользователями, которые активировали функцию паролус-шаринга!</p>
                <div id="passwordShareModal">
                    <div>
                        <Dropdown v-model="selectedReciever" :options="recievingUsers" optionLabel="username" placeholder="С кем поделиться?" class="w-full md:w-14rem" />
                    </div>
                    <div>
                        <Button label="Поделиться" icon="pi pi-external-link" @click="shareParolus" />
                    </div>
                </div>
            </Dialog>
        </div>
    </section>

</template>

<script setup>
import SpeedDial from 'primevue/speeddial';
import Button from 'primevue/button';
import Dialog from 'primevue/dialog';
import Toast from 'primevue/toast';
import InputText from 'primevue/inputtext';
import Password from 'primevue/password';
import Card from 'primevue/card';
import DataView from 'primevue/dataview';
import DataViewLayoutOptions from 'primevue/dataviewlayoutoptions';
import TabView from 'primevue/tabview';
import TabPanel from 'primevue/tabpanel';
import Divider from 'primevue/divider';
import ConfirmDialog from 'primevue/confirmdialog';
import Dropdown from 'primevue/dropdown';
import InputSwitch from 'primevue/inputswitch';
import store from '@/plugins/store';

import { useToast } from 'primevue/usetoast';
import { ref, watch, computed, onBeforeMount, onUpdated } from 'vue';

// import { onRenderTracked, onRenderTriggered } from 'vue'

// onRenderTracked((event) => {
//   debugger
// })

// onRenderTriggered((event) => {
//   debugger
// })

const passwordData = ref(null);
const toast = useToast();
const visibleAddModal = ref(false);
const valueTitle = ref(null);
const valueLogin = ref(null);
const valuePassword = ref(null);
const visibleAboutModal = ref(false);
const visibleEditModal = ref(false);
const visibleShareModal = ref(false);
const editID = ref(null);
const isGenerated = ref(false);
const generatedPassword = ref(null);
const isCopied = ref(false);
const passwordChange = ref(null);
const visibleConfirmDelete = ref(false);
const visibleConfirmDeleteSelfAccount = ref(false);
const valueSearch = ref(null);
const layout = ref('grid');

const isRecievingShares = ref(true);
const recieving = ref(store.state.userStatus);
const isCooldown = ref(false);
const cooldownDuration = 30000;
const remainingCooldown = ref(0);
const recievingUsers = ref(null);
const selectedReciever = ref(null);

// ---------------------------------------------------------------------------------------------->>>>>>>>> //
// ---------------------------------------------------------------------------------------------->>>>>>>>> //
// ---------------------------------------------------------------------------------------------->>>>>>>>> //
onBeforeMount(() => {
    passwordData.value = store.state.passwordData;
    recieving.value = store.state.userStatus;
    recievingUsers.value = store.state.recievingUsers;
})


onUpdated(() => {
    getData();
    checkToken();
    passwordData.value = store.state.passwordData;
    recieving.value = store.state.userStatus;
    recievingUsers.value = store.state.recievingUsers;
    console.log('Component updated');
})

async function getData() {
    await store.dispatch('getPasswordData');
}

async function checkToken() {
    await store.dispatch('checkTokenExpiration');
    console.log('Token expiration time checked');
}

const filteredData = computed(() => {
    if (valueSearch.value !== null) {
        return passwordData.value.filter(x => x.title.toLowerCase().includes(valueSearch.value.toLowerCase())
    )
    } else {
        return passwordData.value;
    }
})

// ---------------------------------------------------------------------------------------------->>>>>>>>> //
// ---------------------------------------------------------------------------------------------->>>>>>>>> //
// ---------------------------------------------------------------------------------------------->>>>>>>>> //
const selectedTheme = ref({ name: 'Аквамариновый', code: 'teal' });
const themes = ref([
    { name: 'Аквамариновый', code: 'teal' },
    { name: 'Индиго', code: 'indigo' },
    { name: 'Янтарный', code: 'amber' },
    { name: 'Небесный', code: 'cyan' },
    { name: 'Фиалковый', code: 'purple' },
    { name: 'Лазурный', code: 'blue' },
    { name: 'Фуксия', code: 'pink' }
])

function toggleTheme() {
    const themeLink = document.getElementById('theme-link');
    if (themeLink.href.includes('lara-light-' + selectedTheme.value.code)) {
        themeLink.href = '/themes/lara-dark-' + selectedTheme.value.code + '/theme.css';
    } else {
        themeLink.href = '/themes/lara-light-' + selectedTheme.value.code + '/theme.css';
    }
}

function switchTheme() {
    const themeLink = document.getElementById('theme-link');
    store.dispatch('updateTheme', selectedTheme.value)
    themeLink.href = '/themes/lara-light-' + selectedTheme.value.code + '/theme.css';
}

onBeforeMount(() => {
  const storedTheme = localStorage.getItem('theme');
  if (storedTheme) {
    selectedTheme.value = JSON.parse(storedTheme);
    switchTheme(selectedTheme.value);
  }
});

watch(selectedTheme, (newTheme) => {
  localStorage.setItem('theme', JSON.stringify(newTheme));
  switchTheme(newTheme);
});

// ---------------------------------------------------------------------------------------------->>>>>>>>> //
// ---------------------------------------------------------------------------------------------->>>>>>>>> //
// ---------------------------------------------------------------------------------------------->>>>>>>>> //
async function addParolus() {
    await store.dispatch('addParolus', {
        title: valueTitle.value,
        login: valueLogin.value,
        password: valuePassword.value
      });
    valueTitle.value = null;
    valueLogin.value = null;
    valuePassword.value = null;
    generatedPassword.value = null;
    visibleAddModal.value = false;
    isCopied.value = false;
    toast.add({ severity: 'success', summary: 'Добавлено', detail: 'Паролуc успешно добавлен', life: 3000 });
}

async function deleteParolus() {
    await store.dispatch('deleteParolus', {
        id: editID.value,
      });
      editID.value = null;
      visibleConfirmDelete.value = false;
      toast.add({ severity: 'success', summary: 'Успешно', detail: 'Паролус удален', life: 3000 });
}

async function shareParolus() {
    try {
        await store.dispatch('shareParolus', {
        parolus_id: editID.value,
        user_id: selectedReciever.value.id
      });
        editID.value = null;
        selectedReciever.value = null;

        visibleShareModal.value = false;
        isCopied.value = false;
        toast.add({ severity: 'success', summary: 'Отправлено', detail: 'Вы поделились паролусом', life: 3000 });
    } catch(error) {
        editID.value = null;
        selectedReciever.value = null;

        visibleShareModal.value = false;
        isCopied.value = false;
        toast.add({ severity: 'error', summary: 'Ошибка', detail: 'Ошибка сервера или пользователь не принимает паролусы', life: 3000 });
    }
}

async function editParolus() {
    await store.dispatch('editParolus', {
        id: editID.value,
        title: valueTitle.value,
        login: valueLogin.value,
        password: valuePassword.value,
      });
    valueTitle.value = null;
    valueLogin.value = null;
    valuePassword.value = null;
    editID.value = null;
    visibleEditModal.value = false;
    toast.add({ severity: 'success', summary: 'Изменено', detail: 'Паролус успешно изменен', life: 3000 });
}

// Пользовательский аккаунт //
async function deleteSelfUserAccount() {
    await store.dispatch('deleteSelfUserAccount');
}

async function changePass() {
    if(passwordChange.value != null) {
    try {
        await store.dispatch('changePassword', {
        new_password: passwordChange.value,
      });
      toast.add({ severity: 'success', summary: 'Изменено', detail: 'Паролус от аккаунта успешно изменен', life: 3000 });
      passwordChange.value = null;
    } catch (error) {
        toast.add({ severity: 'error', summary: 'Ошибка', detail: 'Ошибка смены паролуса от аккаунта', life: 3000 });
    }} else {
        toast.add({ severity: 'info', summary: 'Ошибка', detail: 'Заполните поле нового паролуса', life: 3000 });
    }
}

// ---------------------------------------------------------------------------------------------->>>>>>>>> //
// ---------------------------------------------------------------------------------------------->>>>>>>>> //
// ---------------------------------------------------------------------------------------------->>>>>>>>> //
function editModalOpen(obj) {
    valueTitle.value = obj.title;
    valueLogin.value = obj.login;
    valuePassword.value = obj.password;

    editID.value = obj.id;
    visibleEditModal.value = true;
    isCopied.value = false;
}

function confirmModalOpen(obj) {
    editID.value = obj.id;
    visibleConfirmDelete.value = true;
}

function confirmDeleteSelfAccountModalOpen() {
    visibleAboutModal.value = false;
    visibleConfirmDeleteSelfAccount.value = true;
}

function shareModalOpen(obj) {
    visibleShareModal.value = true;
    editID.value = obj.id;

    recievingUsers.value = store.state.recievingUsers;
}

function closeConfirm() {
    visibleConfirmDelete.value = false;
    visibleConfirmDeleteSelfAccount.value = false;
    toast.add({ severity: 'info', summary: 'Отменено', detail: 'Действие отменено', life: 3000 });
}

watch(recieving, async (newValue, oldValue) => {
  if (newValue !== oldValue) {
    try {
      await store.dispatch('changeStatus', {
        new_status: recieving.value,
      });
      console.log('newValue !== oldValue');

      isCooldown.value = true;
      remainingCooldown.value = cooldownDuration / 1000;

      const cooldownInterval = setInterval(() => {
        remainingCooldown.value -= 1;
        if (remainingCooldown.value <= 0) {
          isCooldown.value = false;
          clearInterval(cooldownInterval);
        }
      }, 1000);

    } catch (error) {
      console.error('Error:', error);
    }
  }
});

function togglePasswordVisibility(obj) {
    obj.visible = !obj.visible;
}

// ---------------------------------------------------------------------------------------------->>>>>>>>> //
// ---------------------------------------------------------------------------------------------->>>>>>>>> //
// ---------------------------------------------------------------------------------------------->>>>>>>>> //
function copyPassword(index) {
    if (passwordData.value[index].visible == true) {
        navigator.clipboard.writeText(passwordData.value[index].password);
        toast.add({ severity: 'success', summary: 'Скопировано', detail: 'Пароль паролуса скопирован в буфер', life: 3000 });
    } else {
        toast.add({ severity: 'error', summary: 'Ошибка', detail: 'Пароль паролуса не видно', life: 3000 });
    }
}

function generatePassword() {
    const length = Math.floor(Math.random() * (16 - 8 + 1)) + 8;
    const uppercaseLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    const lowercaseLetters = 'abcdefghijklmnopqrstuvwxyz';
    const numbers = '0123456789';

    generatedPassword.value += uppercaseLetters[Math.floor(Math.random() * uppercaseLetters.length)];
    generatedPassword.value += numbers[Math.floor(Math.random() * numbers.length)];

    const characters = uppercaseLetters + lowercaseLetters + numbers;
    for (let i = 0; i < length - 2; i++) {
        generatedPassword.value += characters[Math.floor(Math.random() * characters.length)];
    }

    generatedPassword.value = generatedPassword.value.split('').sort(() => Math.random() - 0.5).join('');
    isGenerated.value = true;
}

function copyGenerated() {
    const generated = document.getElementById("generated").textContent;
    navigator.clipboard.writeText(generated);
    isCopied.value = true;
}

function downloadPasswordDataAsJSON() {
    const localStorageData = JSON.parse(localStorage.getItem('vuex'));

    if (!localStorageData || !localStorageData.passwordData || localStorageData.passwordData.length === 0) {
        console.error('No password data found in local storage.');
        return;
    }

    const passwordData = localStorageData.passwordData;
    const jsonData = JSON.stringify(passwordData, null, 2);
    const blob = new Blob([jsonData], { type: 'application/json' });
    const a = document.createElement('a');

    a.href = window.URL.createObjectURL(blob);
    a.download = 'Paroluses.json';
    document.body.appendChild(a);

    a.click();
    
    document.body.removeChild(a);
}
function toGit() {
    window.open('https://gitverse.ru/internetfriend/parolus/', '_blank').focus();
}

// ---------------------------------------------------------------------------------------------->>>>>>>>> //
// ---------------------------------------------------------------------------------------------->>>>>>>>> //
// ---------------------------------------------------------------------------------------------->>>>>>>>> //
const dialLinks = ref([
    {
        label: 'Add',
        icon: 'pi pi-plus',
        command: () => {
            valueTitle.value = null;
            valueLogin.value = null;
            valuePassword.value = null;
            generatedPassword.value = null;
            isGenerated.value = false;
            visibleAddModal.value = true;
        }
    },
    {
        label: 'User',
        icon: 'pi pi-user',
        command: () => {
            visibleAboutModal.value = true;
        }
    },
    {
        label: 'Download',
        icon: 'pi pi-download',
        command: () => {
            downloadPasswordDataAsJSON();
        }
    },
    {
        label: 'Theme',
        icon: 'pi pi-sun',
        command: () => {
            toggleTheme();
        }
    },
    {
        label: 'Logout',
        icon: 'pi pi-sign-out',
        command: () => {
            store.dispatch('logout');
        }
    }
])
</script>

<style scoped lang="css">
.homeCanvas {
    width: 100%;
    height: 100%;

    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: center;
}
.paginatorNav {
    display: flex;
    align-items: center;
}
.paginatorNav:deep(input) {
    margin-right: 1rem;
}
.canvasPasswords {
    width: 100%;
    height: 80%;

    padding: 0 1.5rem 2rem 1.5rem;

    display: flex;
    flex-direction: row;
    justify-content: center;
    flex-wrap: wrap;

    overflow: auto;
}
.canvasDial {
    width: 100%;
    height: 20%;
}
.canvasDial:deep(div) {
    margin-bottom: 2rem;
}
.canvasDial:deep(a) {
    text-decoration: none;
}
#passwordCreationModal {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    padding: 1rem;
}
#passwordCreationModal:deep(input) {
    width: 220px;
}
#passwordCreationModal:deep(small) {
    margin: 0.5rem 0 1rem 0;
}
#passwordCreationModal:deep(button) {
    margin: 1rem 0 0 0;
}
.passwordCreationModal__Generated {
    display: flex;
    justify-content: center;
    align-items: center;

    width: auto;
    padding: 1rem;
    border: 2px solid var(--primary-color);
    border-radius: 1rem;
}
.passwordCreationModal__Generated:deep(i) {
    cursor: pointer;
}
.passwordCreationModal__Generated:deep(i:hover) {
    cursor: pointer;
    color: var(--primary-color);

    transition: 0.3s ease-in-out;
}
#generated {
    margin: 1rem;
}
.passwordCreationModal__Help {
    font-size: small;
    margin: 0 0 0.5rem 0;
}
#aboutModal:deep(button) {
    margin: 1rem 0 0 0;
}
#aboutModal:deep(i) {
    margin: 0 1rem 0 0;
}
#passwordShareModal:deep(button) {
    margin: 1rem 0 0 0;
}
.aboutModal__ContactInfo {
    display: flex;
    align-items: center;

    margin: 0 0 1rem 0;
}
.aboutModal__Themes {
    display: flex;
    flex-direction: column;
}
.passwordCard {
    width: 300px;
    height: auto;

    margin: 1rem;
}
.passwordPanel {
    flex-basis: 100%;
    height: auto;

    margin: 1rem;
}
.passwordPanel:deep(i:hover) {
    cursor: pointer;
    color: var(--primary-color);

    transition: 0.3s ease-in-out;
}
.passwordPanel__title {
    display: flex;
    align-items: center;
}
.passwordPanel__title p {
    font-weight: bold;
    margin: 0 0 0 1rem;
}
.passwordPanel__main {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.passwordPanel__mainText {
    display: flex;
    align-items: center;
}
.passwordPanel__mainText__left {
    margin: 0rem 0.5rem 0rem 48px;
}
.passwordPanel__icons:deep(i) {
    margin-left: 8px;
}
.passwordCardTitle {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.passwordCardTitle__Text {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.passwordCard:deep(i) {
    cursor: pointer;
}

.passwordCard:deep(i:hover) {
    cursor: pointer;
    color: var(--primary-color);

    transition: 0.3s ease-in-out;
}

.passwordIcons {
    display: flex;
    justify-content: space-between;
}

.passwordIcons:deep(i) {
    cursor: pointer;
}

.passwordIcons__primary:deep(i) {
    margin-right: 8px;
}
.confirmButtons:deep(button) {
    margin: 0.5rem;
}
.p-dataview {
    width: 100%;
    height: auto;

    display: flex;
    flex-direction: column-reverse;
    justify-content: flex-end;
}
section:deep(.p-dataview-layout-options) {
    display: flex;
}
section:deep(.p-dropdown) {
    margin: 0.5rem 0 0.5rem 0;
}
section:deep(.p-dataview-content) {
    max-width: 100%;

    display: flex;
    justify-content: center;
    flex-wrap: wrap;
}
.p-divider {
    margin: 0;
}
section:deep(.p-paginator-right-content) {
    margin-left: 1rem;
}
section:deep(.list-enter-active,
.list-leave-active) {
  transition: all 0.5s ease;
}
section:deep(.list-enter-from,
.list-leave-to) {
  opacity: 0;
  transform: translateX(30px);
}
</style>